#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import rospy
from std_msgs.msg import Int32
import os   # sudo apt install sox

def myhook():
    print("shutdown time!")

def myAccuracy_CB(data):
    # 全局变量
    global expected_cmd_nums
    global total_cmd_nums
    global t0
    global flag

    # # 控制接收频率 
    # rate = rospy.Rate(1)
    # rate.sleep()
    t1 = rospy.Time.now().to_sec() - t0 # 当前时刻
    # 测试1分钟的准确率
    if(t1 <= 40):
        print(t1)
        if (data.data == key):
            expected_cmd_nums = expected_cmd_nums + 1
        total_cmd_nums = total_cmd_nums + 1
    else:
        if (flag == True):
            my_accuracy = float(expected_cmd_nums) / total_cmd_nums
            print(("key: %d" %key))
            print(("total_cmd_nums: %d" %total_cmd_nums))
            print(("expected_cmd_nums: %d" %expected_cmd_nums))
            print(("my_accuracy: %f" %my_accuracy))
            os.system('play --no-show-progress --null --channels 1 synth %s sine %f' % (duration, freq)) # 结束声音
            flag = False

def myAccuracy():
    # 初始化节点
    rospy.init_node('myAccuracy')
    # 记录开始时间
    global t0
    t0 = rospy.Time.now().to_sec()  
    # 创建接收器
    rospy.Subscriber('/pub_test', Int32, myAccuracy_CB, queue_size=1, buff_size=52428800)
    rospy.spin()

if __name__ == "__main__":
    '''
        key 关键字对应的命令:
            1 : 队形缩小
            2 : 加速
            3 : 三角形
            4 : 左转
            5 : 停止
            6 : 右转
            7 : 自动控制
            8 : 队形放大
            9 : 减速
            10 : 条形
    '''
    key = 3                 # 当前指定的命令
    t0 = 0.02               # 初始时刻
    total_cmd_nums = 0      # 收到总命令数
    expected_cmd_nums = 0   # 期望命令数
    duration = 1            # second
    freq = 440              # Hz
    flag = True             
    myAccuracy()
    rospy.on_shutdown(myhook)


    '''
        受试者:ys-ys3-real-2s
            命令类型:              准确率
            1 : 队形缩小           0.968153


            2 : 加速               0.981132

            3 : 三角形              0.952342

            4 : 左转              0.989678

            5 : 停止                0.981848


            6 : 右转                 0.974412


            7 : 自动控制            0.883895

            8 : 队形放大            0.994154


            9 : 减速                 0.644765
            10 : 条形               0.994123

    '''





















